package com.lihui.binarytree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2022/11/02  16:54
 */
public class BinaryTreeNotRec {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public  TreeNode root;

    /**
     * 前序遍历
     *
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;
        while(current != null || !stack.isEmpty()){
            while(current != null){
                stack.push(current);
                list.add(current.val);
                current = current.left;
            }
            TreeNode top = stack.pop();
            current = top.right;
        }
        return list;
    }
    /**
     * 中序遍历
     *
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list  = new ArrayList<>();
        if(root == null){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;
        while(current != null || !stack.isEmpty()){
            while(current != null){
                stack.push(current);
                current = current.left;
            }
            TreeNode top = stack.pop();
            list.add(top.val);
            current = top.right;
        }
        return list;
    }
    /**
     * 后续遍历
     */
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;
        TreeNode prev = null;
        while(current != null || !stack.isEmpty()){
            while(current != null){
                stack.push(current);
                current = current.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || top.right == prev){
                list.add(top.val);
                stack.pop();
                prev = top;
            }else{
                current = top.right;
            }
        }
        return list;
    }
}
